<?php
/**
 * 内容页抓取工具。
 */

namespace App\Handlers;

use Goutte\Client;
use Symfony\Component\DomCrawler\Crawler;
use App\Models\CrawlerUrl;
use Illuminate\Support\Str;
use App\Models\CrawlerFilter;
class CrawlerArticleHandler
{
    // 默认标签选择器 （获取头像）
    protected $filters = [
        'www.qqyou.com' => [
            'title' => '.md > h1',
            'content' => '',
            'images' => '.qqtx > p > a > img',
        ],
        'www.woyaogexing.com' => [
            'title' => 'h1',
            'content' => '',
            'images' => '.artCont > li > a > img',
        ],
        'www.qqtn.com' => [
            'title' => 'h1',
            'content' => '#content > p',
            'images' => '#content > p > img',
        ]
    ];
    // 图片标签选择器
    protected $img_filters = [
        'www.qqyou.com' => [
            'title' => '.md > h1',
            'content' => '',
            'images' => '.qqtx > p > a > img',
        ],
        'www.woyaogexing.com' => [
            'title' => 'h1',
            'content' => '',
            'images' => '.artCont > p > a > img',
        ],
        'www.qqtn.com' => [
            'title' => 'h1',
            'content' => '#zoom > p',
            'images' => '#zoom > p > img',
        ]
    ];

    protected $crawler, $filter, $content = '',$category_id = 0,$images = [];
    protected $origin_url_id;


    public function __construct($crawler_url)
    {
        $this->category_id = $crawler_url->category_id;
        $url = $crawler_url->url;
        $this->url = $url;
        $this->baseUri = parse_url($url, PHP_URL_HOST);
        $this->urlinfo = parse_url($url);
        $this->tags = $crawler_url->tags;
        $this->origin_url_id = $crawler_url->origin_url_id;
        $this->getFilter();
        // 获取 html
        $this->getHtml();
    }

    // 获取匹配规则
    private function getFilter()
    {
        $this->filter = CrawlerFilter::where('origin_url_id', $this->origin_url_id)->first();
    }
    public function getResult()
    {
        if(! $this->filter) {
            // 没有设置匹配规则 跳过这个地址
            return ;
        } else {
            // 返回抓取到的数据
            return [
                'title' => $this->getTitle(),
                'content' => $this->getContent(),
                'images' => $this->getImages(),
                'category_id' => $this->category(),
                'tags' => $this->tags
            ];
        }
    }

    public function getHtml()
    {
        if(!$this->filter) {
            return ;
        }
        $http = new Client;
        return $this->crawler = $http->request('GET', $this->url);
    }

    public function getTitle()
    {
        return $this->crawler->filter($this->filter->title_filter)->text();
    }

    public function getContent()
    {
        $text = '';
        if(!empty($this->filter->content)) {
            $this->crawler->filter($this->filter->content_filter)->each(function ($node) use ($text){
                $this->content .= $node->text();
            });
        }
        return $this->content;
    }
    public function category()
    {
        return $this->category_id;
    }
    public function getImages()
    {
        $this->crawler->filter($this->filter->images_filter)->each(function ($node) {
            $src = $node->attr('src');

            if(!Str::startsWith($src, ['https://', 'http://'])) {
                // 如果地址没有协议，类似于（//www.a.com/1.jpg）进行拼接
                $this->images[] = $this->urlinfo['scheme'] . '://' .ltrim($src,'/');
            } else {
                $this->images[] = $src;
            }
        });
        return $this->images;
    }
}
